package com.sinosoft.vaccinetoai.server.business.h3cai.workflowchat.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sinosoft.vaccinetoai.security.model.CustomPrincipal;
import com.sinosoft.vaccinetoai.security.utils.SecurityUtils;
import com.sinosoft.vaccinetoai.utils.h3cai.H3cAlApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import com.sinosoft.vaccinetoai.server.business.h3cai.workflowchat.io.WorkflowChatIO;
import com.sinosoft.vaccinetoai.server.business.h3cai.workflowchat.vo.WorkflowChatVO;
import com.sinosoft.vaccinetoai.server.business.h3cai.workflowchat.service.IWorkflowChatService;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName: WorkflowChatServiceImpl
 * @ClassNameExplain: 
 * @Description: 工作流聊天接口Service Impl
 * @author xzh
 * @date 2025年06月24日 15:33
 */
@Slf4j
@Service("WorkflowChatService")
public class WorkflowChatServiceImpl implements IWorkflowChatService {

	@Resource
	private H3cAlApiUtil h3cAlApiUtil;
	
	@Override
	public Flux<String> workflowChat(WorkflowChatIO io) throws Exception {
		try {
			return Flux.create(emitter -> {
				// 放入你定义的线程池中异步执行，避免阻塞主线程
				H3cAlApiUtil.ASYNC_STREAM_RESPONSE_EXECUTOR_SERVICE.execute(() -> {
					try {
						h3cAlApiUtil.chatReqApi("/api/hub/open/v2/arrange/completions", io.getParams(), (message, status) -> {
							if (status == 1 && message != null) {
								emitter.next(message); // 你原始数据已带 data:，无需再封装
							} else if (status == 2) {
								emitter.complete();
							}
						}, io.getStream());
						emitter.complete();
					} catch (Exception e) {
						emitter.error(e);
					}
				});
			});
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 处理请求
	 * 发送请求、解析消息判断状态进行计费
	 * @param io 入参
	 * @param emitter 响应
	 * @param principal 当前登录人
	 * @since 1.0.3
	 */
	private void handleReq(WorkflowChatIO io, ResponseBodyEmitter emitter, CustomPrincipal principal) {
		try {
			AtomicInteger sendMsgCount = new AtomicInteger();
			h3cAlApiUtil.chatReqApi("/api/hub/open/v2/arrange/completions",io.getParams(), (message, status) -> {
				/**
				 * 正发送中
				 * 解析消息，判断状态，取出结算Token数
				 */
				if(1 == status) {
					try {
						log.info("WorkflowCha消息响应：======》{}",message.toString());
						if ("retry:3000".equals(message)){
							return;
						}
						if(0 != sendMsgCount.getAndIncrement()) {
							emitter.send("\n" + message);
						}else {
							emitter.send(message);
						}
					} catch (IOException e) {
						log.error("WorkflowChat失败响应：{}",e.toString());
					}
					return;
				}
				// 失败或完成
				emitter.complete();
			}, io.getStream());
		} catch (Exception e) {
			emitter.completeWithError(e);
		}
	}
	
}